package xueqiu2

import (
	"io/ioutil"
	logger "log"
	"net/http"
	"net/http/cookiejar"

	"gitee.com/lenchu/stock-api-go/api"
	"gitee.com/lenchu/stock-api-go/utils"
	"github.com/tidwall/gjson"
)

const (
	base_url        = "https://xueqiu.com"
	get_by_code_url = "https://stock.xueqiu.com/v5/stock/quote.json?symbol="

	logger_prefix = "[Xueqiu2] "
)

var log = logger.New(logger.Writer(), logger_prefix, logger.Flags())

type _StockService struct {
	Client *http.Client
}

func (this *_StockService) GetByCode(code string) *api.Stock {
	// TODO 标准Code转换
	url := get_by_code_url + code
	log.Println(url)
	resp, err := this.getWithRetry(url)
	if err != nil {
		return nil
	}
	byteBody, err := ioutil.ReadAll(resp.Body)
	strBody := string(byteBody)
	stockJson := gjson.Get(strBody, "data.quote")
	stock := api.Stock{
		Code:       code,
		Name:       stockJson.Get("name").String(),
		Price:      stockJson.Get("current").String(),
		UpdateTime: utils.TimestampToTime(stockJson.Get("timestamp").String()),
	}
	return &stock
}
func (this *_StockService) SearchStock(keyword string) []*api.Stock {
	return nil
}
func (this *_StockService) BatchGetByCode(codes []string) map[string]*api.Stock {
	return nil
}

func (this *_StockService) getWithRetry(url string) (resp *http.Response, err error) {
	req, err := http.NewRequest(http.MethodGet, url, nil)
	if err != nil {
		return
	}
	client := this.Client
	resp, err = client.Do(req)
	if resp.StatusCode == http.StatusBadRequest {
		if this.refreshToken() {
			return this.getWithRetry(url)
		} else {
			log.Panicln("refresh token failed")
		}
	}
	return
}

func (this *_StockService) refreshToken() bool {
	r, err := this.Client.Get(base_url)
	return err == nil && r.StatusCode == http.StatusOK
}

func NewStockService(httpClient *http.Client) api.StockService {
	if httpClient == nil {
		httpClient = http.DefaultClient
	}
	cookie, _ := cookiejar.New(nil)
	httpClient.Jar = cookie
	return &_StockService{
		Client: httpClient,
	}
}
